package com.jmb.waimao.controller;

import com.jmb.waimao.service.MCPEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller for the Mail Control Protocol (MCP) Email Service
 */
@RestController
@RequestMapping("/api/mcp")
@Slf4j
public class MCPEmailController {

    @Autowired
    private MCPEmailService mcpEmailService;

    /**
     * Send a simple email
     *
     * @param to Recipient email address
     * @param subject Email subject
     * @param content Email content (can be HTML)
     * @return Response with success status and message
     */
    @PostMapping("/send")
    public ResponseEntity<Map<String, Object>> sendEmail(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestParam String content) {
        
        log.info("MCP API: Sending email to: {}", to);
        boolean success = mcpEmailService.sendEmail(to, subject, content);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "Email sent successfully" : "Failed to send email");
        
        return ResponseEntity.ok(response);
    }

    /**
     * Send an email with attachments
     *
     * @param to Recipient email address
     * @param subject Email subject
     * @param content Email content (can be HTML)
     * @param attachments Attachments to include
     * @return Response with success status and message
     */
    @PostMapping("/send-with-attachments")
    public ResponseEntity<Map<String, Object>> sendEmailWithAttachments(
            @RequestParam String to,
            @RequestParam String subject,
            @RequestParam String content,
            @RequestParam(required = false) MultipartFile[] attachments) {
        
        log.info("MCP API: Sending email with attachments to: {}", to);
        
        Map<String, byte[]> attachmentMap = new HashMap<>();
        if (attachments != null) {
            for (MultipartFile file : attachments) {
                try {
                    attachmentMap.put(file.getOriginalFilename(), file.getBytes());
                } catch (IOException e) {
                    log.error("MCP API: Failed to read attachment: {}", file.getOriginalFilename(), e);
                }
            }
        }
        
        boolean success = mcpEmailService.sendEmailWithAttachments(to, subject, content, attachmentMap);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "Email sent successfully" : "Failed to send email");
        response.put("attachmentCount", attachmentMap.size());
        
        return ResponseEntity.ok(response);
    }

    /**
     * Send a templated email
     *
     * @param to Recipient email address
     * @param subject Email subject (optional, will use template subject if not provided)
     * @param templateId ID of the template to use
     * @param variables Variables to replace in the template
     * @return Response with success status and message
     */
    @PostMapping("/send-templated")
    public ResponseEntity<Map<String, Object>> sendTemplatedEmail(
            @RequestParam String to,
            @RequestParam(required = false) String subject,
            @RequestParam Long templateId,
            @RequestBody(required = false) Map<String, Object> variables) {
        
        log.info("MCP API: Sending templated email to: {}", to);
        
        if (variables == null) {
            variables = new HashMap<>();
        }
        
        boolean success = mcpEmailService.sendTemplatedEmail(to, subject, templateId, variables);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "Templated email sent successfully" : "Failed to send templated email");
        response.put("templateId", templateId);
        
        return ResponseEntity.ok(response);
    }

    /**
     * Get the status of the email service
     *
     * @return Status information
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getStatus() {
        log.info("MCP API: Getting email service status");
        Map<String, Object> status = mcpEmailService.getStatus();
        return ResponseEntity.ok(status);
    }

    /**
     * Configure the email service
     *
     * @param config Configuration parameters
     * @return Response with success status and message
     */
    @PostMapping("/configure")
    public ResponseEntity<Map<String, Object>> configure(@RequestBody Map<String, Object> config) {
        log.info("MCP API: Configuring email service");
        boolean success = mcpEmailService.configure(config);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "Email service configured successfully" : "Failed to configure email service");
        
        return ResponseEntity.ok(response);
    }
}
